package command.linux;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;

import model.Player;
import command.Command;
import command.CommandFactory;
import config.Debug;
import config.Helper;

public class LinuxCommandFactory extends CommandFactory {

	@Override
	public void rebootSystem() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void restartPlayer() {
		Debug.msg("Restarting Player");
		Debug.log("The Player is restarted.", Debug.SYSTEM_LEVEL);
		File jarFile = null;
		try {
			System.out.println(Player.getInstance().getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
			jarFile = new File(Player.getInstance().getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
		} catch (URISyntaxException ex) {
			Logger.getLogger(Command.class.getName()).log(Level.SEVERE, null, ex);
		}
		try {
			String cmd = "java -Xms256M -Xmx256M -jar dmbplayer.jar";
			Process p = Runtime.getRuntime().exec(cmd, null, jarFile.getParentFile());
		} catch (IOException e) {
			Debug.log("Error while restarting application", Debug.ERROR_LEVEL);
			System.err.println("Error while restarting application");
		}
		System.exit(0);
	}

	@Override
	public void restartTeamViewer() {
		try {
			Process p = Runtime.getRuntime().exec("pidof TeamViewer.exe");
			InputStream is = p.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String result = br.readLine();
			p.destroy();
			
			ProcessBuilder bb = null;
			if(result!=null) {
				  bb = new ProcessBuilder(new String[] {"kill -9 " + result, "teamviewer"});
				
			} else {
				bb = new ProcessBuilder("teamviewer");
			}
			bb.start();
			Debug.log("restarting Teamviewer", Debug.SYSTEM_LEVEL);
		} catch (IOException ex) {
			Debug.log("Error restarting Teamviewer", Debug.ERROR_LEVEL);
		}
	}

	@Override
	public void startTeamViewer() {
		try {
			Process p = Runtime.getRuntime().exec("pidof TeamViewer.exe");
			InputStream is = p.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String result = br.readLine();
			p.destroy();
			
			if(result==null) {
				ProcessBuilder pb = new ProcessBuilder("teamviewer");
				pb.start();
				Debug.log("Starting Teamviewer", Debug.SYSTEM_LEVEL);
			} else {
				
			}
		} catch (IOException ex) {
			Debug.log("Error restarting Teamviewer", Debug.ERROR_LEVEL);
		}
	}

}
